package controllers

import (
	"blog/syserror"
	"github.com/astaxie/beego/logs"
)

type ErrorController struct {
	BaseController
}

// ajax请求 {code:,msg:}
func (c *ErrorController) Error404() {
	c.TplName = "error/404.html"
	if c.IsAjax() {
		c.jsonError(syserror.Error404{})
	}
}

// ajax请求 {code:,msg:}
func (c *ErrorController) Error500() {

	c.TplName = "error/500.html"
	err, ok := c.Data["error"].(error)

	if !ok {
		err = syserror.New(300, "未知错误！~", nil)
	}

	serr, ok := err.(syserror.Error)

	if !ok {
		serr = syserror.New(303, err.Error(), nil)
	}

	if serr.ReasonError() != nil {
		logs.Info(serr.Error(), serr.ReasonError())
	}

	if c.IsAjax() {
		c.jsonError(serr)
	} else {
		c.Data["content"] = err.Error()
	}
}

func (c *ErrorController) jsonError(serr syserror.Error) {

	c.Ctx.Output.Status = 200

	c.Data["json"] = map[string]interface{}{
		"code": serr.Code(),
		"msg":  serr.Error(),
	}

	c.ServeJSON()
}
